<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="老人" prop="elderUserId">
        <el-select
          v-model="queryParams.elderUserId"
          placeholder="请选择老人"
          clearable
          size="small"
          @change="handleQuery"
        >
          <el-option
            v-for="elder in elderOptions"
            :key="elder.userId"
            :label="elder.nickName"
            :value="elder.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="请假类型" prop="leaveType">
        <el-select
          v-model="queryParams.leaveType"
          placeholder="请选择请假类型"
          clearable
          size="small"
          @change="handleQuery"
        >
          <el-option label="事假" value="1" />
          <el-option label="病假" value="2" />
          <el-option label="其他" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          size="small"
          @change="handleQuery"
        >
          <el-option label="待审核" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已拒绝" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="请假时间">
        <el-date-picker
          v-model="queryParams.dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="leaveList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="请假编号" align="center" prop="id" />
      <el-table-column label="老人姓名" align="center" prop="elderName" />
      <el-table-column label="请假类型" align="center" prop="leaveType">
        <template slot-scope="scope">
          <span>{{
            scope.row.leaveType === "1"
              ? "事假"
              : scope.row.leaveType === "2"
              ? "病假"
              : "其他"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="请假原因"
        align="center"
        prop="leaveReason"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.startTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.endTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{
            scope.row.status === "0"
              ? "待审核"
              : scope.row.status === "1"
              ? "已通过"
              : "已拒绝"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="审核备注"
        align="center"
        prop="auditRemark"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-show="scope.row.status !== '1'"
            v-hasPermi="['system:leave:update']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:leave:delete']"
            >删除</el-button
          >
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:leave:audit']"
            >审核</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改请假记录对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      @open="handleOpen"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人" prop="elderUserId">
          <el-select
            v-model="form.elderUserId"
            placeholder="请选择老人"
            @change="handleElderChange"
          >
            <el-option
              v-for="elder in elderOptions"
              :key="elder.userId"
              :label="elder.nickName"
              :value="elder.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请假类型" prop="leaveType">
          <el-select v-model="form.leaveType" placeholder="请选择请假类型">
            <el-option label="事假" value="1" />
            <el-option label="病假" value="2" />
            <el-option label="其他" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="请假原因" prop="leaveReason">
          <el-input
            v-model="form.leaveReason"
            type="textarea"
            placeholder="请输入请假原因"
          />
        </el-form-item>
        <el-form-item label="请假时间" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            size="small"
            style="width: 360px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      :title="'审核请假申请'"
      :visible.sync="auditOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="auditForm"
        :model="auditForm"
        :rules="auditRules"
        label-width="80px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAudit">确 定</el-button>
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLeave,
  getLeave,
  delLeave,
  addLeave,
  updateLeave,
  exportLeave,
} from "@/api/system/leave";
import { listElder } from "@/api/system/user";

export default {
  name: "Leave",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假记录表格数据
      leaveList: [],
      // 老人选项
      elderOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示审核弹出层
      auditOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        elderUserId: null,
        leaveType: null,
        status: null,
        startTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 审核表单参数
      auditForm: {
        id: null,
        status: null,
        auditRemark: null,
      },
      // 表单校验
      rules: {
        elderUserId: [
          { required: true, message: "请选择老人", trigger: "change" },
        ],
        leaveType: [
          { required: true, message: "请选择请假类型", trigger: "change" },
        ],
        leaveReason: [
          { required: true, message: "请输入请假原因", trigger: "blur" },
        ],
        dateRange: [
          { required: true, message: "请选择请假时间", trigger: "change" },
        ],
      },
      // 审核表单校验
      auditRules: {
        status: [
          { required: true, message: "请选择审核结果", trigger: "change" },
        ],
        auditRemark: [
          { required: true, message: "请输入审核备注", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getElderList();
  },
  methods: {
    handleOpen() {
      this.getElderList();
    },
    /** 查询请假记录列表 */
    getList() {
      this.loading = true;
      if (
        this.queryParams.dateRange &&
        this.queryParams.dateRange.length === 2
      ) {
        this.queryParams.startTime = this.queryParams.dateRange[0];
        this.queryParams.endTime = this.queryParams.dateRange[1];
      }
      listLeave(this.queryParams).then((response) => {
        this.leaveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取老人列表 */
    getElderList() {
      listElder().then((response) => {
        this.elderOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消审核按钮
    cancelAudit() {
      this.auditOpen = false;
      this.resetAudit();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        elderUserId: null,
        elderName: null,
        leaveType: null,
        leaveReason: null,
        startTime: null,
        endTime: null,
        status: "0",
      };
      this.dateRange = [];
      this.resetForm("form");
    },
    // 审核表单重置
    resetAudit() {
      this.auditForm = {
        id: null,
        status: null,
        auditRemark: null,
      };
      this.resetForm("auditForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加请假记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getLeave(id).then((response) => {
        this.form = response.data;
        this.dateRange = [this.form.startTime, this.form.endTime];
        this.open = true;
        this.title = "修改请假记录";
      });
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.resetAudit();
      this.auditForm.id = row.id;
      this.auditOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.dateRange && this.form.dateRange.length === 2) {
            this.form.startTime = this.form.dateRange[0];
            this.form.endTime = this.form.dateRange[1];
          }
          if (this.form.id != null) {
            updateLeave(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLeave(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs["auditForm"].validate((valid) => {
        if (valid) {
          updateLeave(this.auditForm).then((response) => {
            this.$modal.msgSuccess("审核成功");
            this.auditOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除请假记录编号为"' + ids + '"的数据项？')
        .then(function () {
          return delLeave(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/leave/export",
        {
          ...this.queryParams,
        },
        `leave_${new Date().getTime()}.xlsx`
      );
    },
    /** 老人选择改变 */
    handleElderChange(value) {
      const elder = this.elderOptions.find((item) => item.userId === value);
      if (elder) {
        this.form.elderName = elder.nickName;
      }
    },
  },
};
</script>
